package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.fragment.ChooseFriendDialogFragment.OnChooseFriendDialogFragment;
import com.nullpointer.xchatfinal.object.SelectFriend;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBGroupChatManager;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.core.QBEntityCallbackImpl;

public class CreateGroupDialogFragment extends DialogFragment {
	private EditText etName;
	private TextView tvPublicGroup;
	private TextView tvPrivateGroup;
	private TextView tvMember;
	private LinearLayout llMember;
	private TextView tvNote;
	private Button btCreate;
	private Button btCancel;
	private int focus = Color.parseColor("#ff8800");
	private int normal = Color.parseColor("#333333");
	private boolean isPublicGroup = true;
	private final String privateNote = "Private group: only member can join this group.";
	private final String publicNote = "Public group: any user can join this group.";
	private List<String> userIDs = new ArrayList<String>();
	private List<String> userNames = new ArrayList<String>();
	private OnCreateGroupDialogFragment listener;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_create_group, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		tvPublicGroup.setTextColor(focus);
		tvPrivateGroup.setTextColor(normal);
		showInfo("Name must > 3 char", false);
		tvNote.setText(publicNote);
		llMember.setVisibility(View.GONE);
	}

	private void setEvent() {
		llMember.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					final ChooseFriendDialogFragment dialog = ChooseFriendDialogFragment
							.newInstance(null, new ArrayList<>(userIDs));
					dialog.setOnChooseFriendDialogFragment(new OnChooseFriendDialogFragment() {

						@Override
						public void onChooseFriend(
								final List<SelectFriend> users) {
							userIDs.clear();
							userNames.clear();
							if (users.size() == 0) {
								return;
							}
							KiraGameLog.d("list choose friend " + users);

							for (SelectFriend user : users) {
								userIDs.add(user.getUserID());
								userNames.add(user.getUserName());
							}
							tvMember.setText(TextUtils.join(", ", userNames));
						}

						@Override
						public void onCancel() {

						}
					});
					FragmentTransaction transaction = getActivity()
							.getSupportFragmentManager().beginTransaction();
					transaction.add(dialog, "ChooseFriendDialogFragment");
					transaction.commitAllowingStateLoss();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		btCreate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(getActivity(), etName);
				createGroup();
			}
		});

		btCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});

		etName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etName.getText() != null
						&& etName.getText().toString().trim().length() >= 3) {
					if (Utils.checkBadword(etName.getText().toString())) {
						showInfo("Don't use sexual content!", false);
					} else {
						hideInfo();
					}
				} else {
					showInfo("Name must > 3 char", false);
				}
			}
		});

		tvPublicGroup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!isPublicGroup) {
					tvPublicGroup.setTextColor(focus);
					tvPrivateGroup.setTextColor(normal);
					isPublicGroup = true;
					tvNote.setText(publicNote);
					llMember.setVisibility(View.GONE);
				}

			}
		});
		tvPrivateGroup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isPublicGroup) {
					tvPrivateGroup.setTextColor(focus);
					tvPublicGroup.setTextColor(normal);
					isPublicGroup = false;
					tvNote.setText(privateNote);
					llMember.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	private void showInfo(String info, boolean isClickable) {
		btCreate.setText(info);
		btCreate.setEnabled(isClickable);
		btCancel.setVisibility(View.GONE);
	}

	private void hideInfo() {
		btCreate.setText("Create");
		btCreate.setEnabled(true);
		btCancel.setVisibility(View.VISIBLE);
	}

	protected void createGroup() {
		showInfo("Creating group...", false);
		ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
		occupantIdsList.add(DataManager.getInstance(getActivity())
				.getCurrentUser().getUserID());

		QBDialog dialog = new QBDialog();
		dialog.setName(etName.getText().toString());
		// dialog.setPhoto("1786");

		if (isPublicGroup) {
			dialog.setType(QBDialogType.PUBLIC_GROUP);
		} else {
			dialog.setType(QBDialogType.GROUP);
			for (String id : userIDs) {
				occupantIdsList.add(Integer.parseInt(id));
			}

		}
		dialog.setOccupantsIds(occupantIdsList);

		QBGroupChatManager groupChatManager = QBChatService.getInstance()
				.getGroupChatManager();
		groupChatManager.createDialog(dialog,
				new QBEntityCallbackImpl<QBDialog>() {
					@Override
					public void onSuccess(QBDialog mDialog, Bundle args) {
						if (listener != null) {
							listener.onCreated(mDialog);
						}
						hideInfo();
						dismiss();
					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("createGroup errors " + errors);
						showInfo("Try again!", true);
					}
				});
	}

	private void findViewIds(View view) {
		etName = (EditText) view.findViewById(R.id.et_name);
		tvPublicGroup = (TextView) view.findViewById(R.id.tv_public_group);
		tvPrivateGroup = (TextView) view.findViewById(R.id.tv_private_group);
		tvMember = (TextView) view.findViewById(R.id.tv_member);
		llMember = (LinearLayout) view.findViewById(R.id.ll_member);
		tvNote = (TextView) view.findViewById(R.id.tv_note);
		btCreate = (Button) view.findViewById(R.id.bt_create);
		btCancel = (Button) view.findViewById(R.id.bt_cancel);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		Utils.hideKeyboard(getActivity(), etName);
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		super.onCancel(dialog);
		Utils.hideKeyboard(getActivity(), etName);
	}

//	protected void showChooseImageFragment() {
//		final ChooseImageDialogFragment dialog = new ChooseImageDialogFragment();
//		dialog.setOnChooseImageDialogFragment(new OnChooseImageDialogFragment() {
//
//			@Override
//			public void onGallery() {
//				selectImageFromGallery();
//			}
//
//			@Override
//			public void onCamera() {
//				selectImageFromCamera();
//			}
//		});
//		FragmentTransaction transaction = getActivity()
//				.getSupportFragmentManager().beginTransaction();
//		transaction.add(dialog, "ChooseImageDialogFragmentEditProfile");
//		transaction.commitAllowingStateLoss();
//	}

//	protected void selectImageFromGallery() {
//		Intent intent = new Intent(getActivity(), ProcessImage.class);
//		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, false);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
//		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
//	}
//
//	protected void selectImageFromCamera() {
//		Intent intent = new Intent(getActivity(), ProcessImage.class);
//		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, true);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
//		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
//	}

	public void setOnCreateGroupDialogFragment(
			OnCreateGroupDialogFragment listener) {
		this.listener = listener;
	}

	public interface OnCreateGroupDialogFragment {
		public void onCreated(QBDialog mDialog);
	}
}
